﻿/******************************************************************************
* File description: DataSerialportClient.cpp
* Function: 纯化监测数据线程
* Current Version: 1.0.0
* Author: 郑佰旺
* Date: 2025-07-1
*  -----
*  Copyright by 博坤生物 .
 *****************************************************************************/

#include "DataSerialportClient.h"
#include <QNetworkDatagram>

DataSerialportClient::DataSerialportClient(QObject *parent): QObject(parent)
{
    this->moveToThread(&thread);
    serialPort = new QSerialPort(this);
    thread.start();
}

/**
 * @brief DataSerialportClient::startAutoSend
 * @param intervalMs 间隔时间
 * @param serialNamePort 端口
 */
void DataSerialportClient::startAutoSend(int intervalMs,QString serialNamePort){
    if(serialPort->isOpen()){
        serialPort->close();
    }
    QSerialPort::BaudRate baudRate;
    baudRate = QSerialPort::Baud115200;
    serialPort->setPortName(serialNamePort);
    serialPort->setBaudRate(baudRate);
    if(serialPort->open(QIODevice::ReadWrite)){

        message ="01 04 00 00 00 02 71 CB";
        QMLSignal::I().emitEnergySpectrumStatus(0);
         QString info="正常";
        StaticProperties::purifyingStatus["5"].setValue(info);
        connect(serialPort,SIGNAL(readyRead()),this,SLOT(handleReadyRead()));// 串口读取

        timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &DataSerialportClient::sendMessage);
        timer->start(intervalMs);
    }
}

/**
 * @brief DataSerialportClient::sendMessage 发送消息
 */
void DataSerialportClient::sendMessage()
{
    data = CommonHelper::Common().GetSendData(message);
    serialPort->write(data);
    messageStatus = true;
}

/**
 * @brief DataSerialportClient::handleReadyRead 处理接收到的消息
 */
void DataSerialportClient::handleReadyRead()
{
    if(StaticProperties::expStatus!=0){
        QByteArray data = serialPort->readAll();
        QString str;
        for(int c :data)
        {
            if(c>=0)
            {
                str += QString(" %1").arg(c, 2, 16, QChar('0')).toUpper();
            }
            else
            {
                str += QString(" %1").arg(c+256, 2, 16, QChar('0')).toUpper();
            }
        }
        str= str.simplified();

        QStringList list=str.split(" ");
        if(list.length()>6){
            double finalData=CommonHelper::Common().SixteenToTen(list[3]+" " +list[4]+" " +list[5]+" "+list[6]).toDouble();
            QSqlDatabase db = dbHelper::openConnection();
            QSqlQuery query(db);
            QString sql=QString("Insert into CPSData Values('%1','%2')").arg(CommonHelper::Common().GetDateTimeStr(),QString::number(finalData));
            query.exec(sql);
            QMLSignal::I().emitSendCpsData(finalData);
            if(StaticProperties::isProductTesting){
                if(StaticProperties::dataThresholdType=="大于"){
                    if(finalData>StaticProperties::dataThreshold){
                        StaticProperties::isProductTesting=false;

                        QSqlDatabase db = dbHelper::openConnection();
                        QSqlQuery query(db);
                        QString sql="Update ExperimentInfo set isProductTesting='false'";
                        query.exec(sql);

                        ExperimentThread::I().run();
                    }
                }
                else if(StaticProperties::dataThresholdType=="小于"){
                    if(finalData<StaticProperties::dataThreshold){
                        StaticProperties::isProductTesting=false;

                        QSqlDatabase db = dbHelper::openConnection();
                        QSqlQuery query(db);
                        QString sql="Update ExperimentInfo set isProductTesting='false'";
                        query.exec(sql);

                        ExperimentThread::I().run();
                    }
                }
            }
        }
    }
}
